
from x_com import xport_core
from x_com import source_api
from x_com import topic
import asyncio
import csv
import x_com_lib
logger = xport_core.getLogger()

class ElectricityDataSourceService:
  # 是否在推送用电量记录数据
  is_monitoring_data: bool

  # 是否在推送充值记录数据
  is_recharge_data: bool

  # 是否在推送充值记录数据
  is_dormitory_data: bool

  async def on_init(self):
    # 获取数据历经
    self.data_path = x_com_lib.config.get_str("data-path")
    # 初始化为 False
    self.is_monitoring_data = False
    self.is_recharge_data = False
    self.is_dormitory_data = False


  async def on_finalize(self):
    logger.info("on_finalize...")

  def _subscribe_data(self, conn_id: int, topic:str):
      subscibe_info = x_com_lib.PySubscribeTopicInfo()
      subscibe_info.topic = topic
      subscibe_info.conn_id = conn_id
      subscibe_info.tag = []
      x_com_lib.stream.xport_subscribe_topic(subscibe_info)
                                             
  # SubscribeData
  async def subscribe_data(self, ctx: xport_core.Context):
    logger.info(f"订阅数据。。。")
    self._subscribe_data(ctx.conn_id, "Monitoring")
    self._subscribe_data(ctx.conn_id, "Recharge")
    self._subscribe_data(ctx.conn_id, "Dormitory")

  # 推送数据
  async def _play_monitoring_data(self):
    # 这里路径需改
    data_path = f"{self.data_path}/monitoring.csv"
    push_num = 0
    with open(data_path, mode='r', encoding='utf-8') as file:
       # 创建一个CSV读取器
       reader = csv.reader(file)
       # 跳过第一行（表头）
       next(reader)
       # 遍历CSV文件中的每一行
       for row in reader:
         # 
         monitoring_info = source_api.MonitoringInfo()
         
         monitoring_info.id = row[0]
         monitoring_info.used = float(row[1])
         monitoring_info.free = float(row[2])
         monitoring_info.remaining = float(row[3])
     
         monitoring_info.record_time = row[4]

         monitoring_info.room_number = row[5]
         monitoring_info.room_name = row[6]
         monitoring_info.meter_address = row[7]

         topic.monitoring(monitoring_info)
         push_num += 1
         if push_num % 1000 == 0:

          logger.info(f"已推送用电量记录数据：{push_num} 条")
         # 100毫秒 推送一条数据
         await asyncio.sleep(0.1)  # 模拟处理延时

    self.is_monitoring_data = False

  # PlayMonitoringData
  async def play_monitoring_data(self, ctx: xport_core.Context):
    if self.is_monitoring_data:
      logger.info("用电量记录在推送中...")
      return
    self.is_monitoring_data = True
    # 开启新的协程去推送，否则会卡住，无法返回
    asyncio.create_task(self._play_monitoring_data())

  # 推送数据
  async def _play_recharge_data(self):
    # 这里路径需改
    data_path = f"{self.data_path}/recharge.csv"
    push_num = 0
    with open(data_path, mode='r', encoding='utf-8') as file:
       # 创建一个CSV读取器
       reader = csv.reader(file)
       # 跳过第一行（表头）
       next(reader)
       # 遍历CSV文件中的每一行
       for row in reader:
         # 
         recharge_info = source_api.RechargeInfo()
         recharge_info.id = row[0]
         recharge_info.recharged = float(row[1])

         recharge_info.recharge_time = row[2]
         recharge_info.recharge_order_number = row[3]
         # 转换为整型
         recharge_info.recharge_amount = float(row[4])
         # 转换为浮点型
         recharge_info.room_number = row[5]
         #  
         recharge_info.room_name = row[6]

         topic.recharge(recharge_info)
         push_num += 1
         if push_num % 100 == 0:
          logger.info(f"已推送充值记录数据：{push_num} 条")
         # 100毫秒 推送一条数据
         await asyncio.sleep(0.1)  # 模拟处理延时

    self.is_recharge_data = False

  # PlayRechargeData
  async def play_recharge_data(self, ctx: xport_core.Context):
    
    if self.is_recharge_data:
      logger.info("充值记录在推送中...")
      return
    self.is_recharge_data = True
    # 开启新的协程去推送，否则会卡住，无法返回
    asyncio.create_task(self._play_recharge_data())


  # 推送数据
  async def _play_dormitory_data(self):
    # 这里路径需改
    data_path = f"{self.data_path}/dormitory.csv"
    push_num = 0
    with open(data_path, mode='r', encoding='utf-8') as file:
       # 创建一个CSV读取器
       reader = csv.reader(file)
       # 跳过第一行（表头）
       next(reader)
       # 遍历CSV文件中的每一行
       for row in reader:
         # 
         recharge_info = source_api.DormitoryInfo()
         recharge_info.floor_name = row[0]
         recharge_info.building_name = row[1]

         recharge_info.personnel_id = row[2]
         recharge_info.bed_number = row[3]
         # 转换为整型
         recharge_info.bed_position = int(row[4])
         recharge_info.occupancy_status = int(row[5])
         # 转换为浮点型
         recharge_info.room_number = int(row[6])

         recharge_info.grade = int(row[7])

         recharge_info.department_id = row[8]
         recharge_info.organization_name = row[9]
         recharge_info.room_id = row[10]
         topic.dormitory(recharge_info)
         push_num += 1
         if push_num % 100 == 0:
          logger.info(f"已推送入住记录数据：{push_num} 条")
         # 100毫秒 推送一条数据
         await asyncio.sleep(0.1)  # 模拟处理延时

    self.is_dormitory_data = False

  # PlayDormitoryData
  async def play_dormitory_data(self, ctx: xport_core.Context):
    if self.is_dormitory_data:
      logger.info("推送入住记录在推送中...")
      return
    self.is_dormitory_data = True
    # 开启新的协程去推送，否则会卡住，无法返回
    asyncio.create_task(self._play_dormitory_data())

  # PlayAllData
  async def play_all_data(self, ctx: xport_core.Context):
    asyncio.create_task(self.play_monitoring_data(ctx))
    asyncio.create_task(self.play_recharge_data(ctx))
    asyncio.create_task(self.play_dormitory_data(ctx))

